package com.study.hisapi.service.hisService;

import cn.hutool.json.JSONUtil;
import com.study.hisapi.constant.HisServiceConstant;
import com.study.hisapi.domain.bo.core.RequestBo;
import com.study.hisapi.exception.*;
import com.study.hisapi.service.AbstractHisService;
import com.study.hisapi.utils.Context;
import com.study.hisapi.utils.ContextUtils;
import com.study.hisapi.utils.SpringReflectUtils;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;

/**
 * 信通 HIS
 *
 * @author LiXiao
 * @date 2024/4/11
 */
@Slf4j
@Service(HisServiceConstant.HIS_XT)
public class HisXTService extends AbstractHisService {

    static Object getResourceObject(@NotNull RequestBo request) {
        Object bean = SpringReflectUtils.getBean(request.getHospital());
        Object resource;
        String method = request.getMethod();

        String requestData = JSONUtil.toJsonStr(request.getRequestData());
        log.info("方法：{}，请求参数：{}", method, requestData);

        Context currentContext = ContextUtils.getCurrentContext();
        currentContext.setMethod(method);
        try {
            resource = SpringReflectUtils.invokeMethod(bean, method, request.getRequestData());
        } catch (NoSuchMethodException e) {
            throw new NotFoundException(method);
        } catch (InvocationTargetException e) {
            if (e.getCause() instanceof MethodNotOverriddenException) {
                MethodNotOverriddenException customEx = (MethodNotOverriddenException) e.getCause();
                throw new MethodNotOverriddenException(customEx.getMessage());
            }
            if (e.getCause() instanceof HisRequestException) {
                HisRequestException customEx = (HisRequestException) e.getCause();
                throw new HisRequestException(customEx.getMessage());
            }
            if (e.getCause() instanceof ValidatedException) {
                ValidatedException customEx = (ValidatedException) e.getCause();
                throw new ValidatedException(customEx.getMessage());
            }
            throw new ServiceException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new ServiceException(e.getMessage());
        }
        Class<?> aClass = resource.getClass();
        log.info("方法：{}，返回类名称：{}，返回结果JSON：{}", method, aClass, JSONUtil.toJsonStr(resource));
        return resource;
    }


    @Override
    public Object handle(RequestBo request) {
        return getResourceObject(request);
    }
}